<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends CommonController {
	
	const SMS_SEND_INTERVAL = 60;
	
    public function index(){
    	echo 'user';
    }
	public function select(){//显示默认头像初始数据
		$this->meta_title='选择擅长您的乐器';
		if($_POST){
			$autoimgid = $_POST['id'];
			$user = M('user')->where(array('id'=>$this->uid))->find();
			$userimg = M('user_autoimg')->where(array('id'=>$autoimgid))->find();
			$user['titlename'] = $userimg['titlename'];
			$user['imgurl'] = $userimg['imgurl'];//头像路径，注册时默认是乐器头像
			$issave = M('user')->save($user);
			$this->ajaxReturn(array('issave'=>$issave,'aid'=>session('look_aid')));
		}else{
			$userimgs = M('user_autoimg');
			$userimg = $userimgs->order(' id desc ')->limit(4)->page(1)->select();
			$this->assign('p',1);
			$this->assign('uid',$this->uid);
			$this->assign('userimg',$userimg);
			$this->display();
		}
	}
	/*
	 * 换一批默认头像
	 * */
	public function reload_userimg(){
		$userimgs = M('user_autoimg');
		$count = $userimgs->count();
		$limit = 4;
		$max_page = $count/$limit;
		if(I('p') && $max_page > I('p')){
			$p = I('p')+1;
		}else{
			$p=1;
		}
		$userimg = $userimgs->order(' id desc ')->limit(4)->page($p)->select();
		$html = '';
		foreach($userimg as $v){
			$html = $html.'<div class="col-xs-6">'.
							'<div class="instrument-div" data-id="'.$v['id'].'" onclick="select(this)">'.
								'<img src="'.$v['imgurl'].'" />'.
							'</div>'.
						  '</div>';	
		}
		$this->ajaxReturn(array('html'=>$html,'p'=>$p));
	}
	public function mystage(){
		$limit = 10;
		$myallact = D('UserActivityJoinView')->where(array('uid'=>$this->uid,'ae_status'=>'1'))->select();
		$p = I('p');
		$count = count($myallact);
		$max_page = $count/$limit;
		if(!$p){
			$p=1;
			$this->situation = 'first';
		}else{
			if($p >= $max_page){
				$this->situation = 'last';
			}else if($p == 1 && $count>$limit){
				$this->situation = 'first';
			}else{
				$this->situation = 'middle';
			}
		}
		if($count<$limit){//只有一页数据
			$this->situation = 'justone';
		}
		$myact = D('UserActivityJoinView')->where(array('uid'=>$this->uid,'ae_status'=>'1'))->order(' aetime desc ')->limit($limit)->page($p)->select();
		$this->myact = $myact;
		$this->p = $p;
		$this->meta_title='我的舞台';
		$this->display();
	}
	public function myset(){
		$this->meta_title='个人设置';
		$this->display();
	}
	public function editset(){
		$this->meta_title='个人设置';
		$this->display();
	}
	/**
	 * 用户修改非图片信息
	 */
	 public function user_edit(){
	 	if(IS_POST){
	 		if($_POST['nickname']){
	 			M('user')->where(array('id'=>$this->uid))->setField('nickname',$_POST['nickname']);
	 		}
			if($_POST['area']){
				M('user')->where(array('id'=>$this->uid))->setField('area',$_POST['area']);
				M('user')->where(array('id'=>$this->uid))->setField('area1',$_POST['area1']);
				M('user')->where(array('id'=>$this->uid))->setField('area2',$_POST['area2']);
				M('user')->where(array('id'=>$this->uid))->setField('area3',$_POST['area3']);
			}
			if($_POST['sex']){
				M('user')->where(array('id'=>$this->uid))->setField('sex',$_POST['sex']);
			}
			$this->ajaxReturn(1);
	 	}
	 }
	 
	 /**
	  * 用户修改头像
	  */
	  public function user_edit_img(){
	  	$upload = get_upload_img(C('USER'));//上传图片至服务器
		if($upload){
			$img = $upload['imgurl'];
			$imgurl = C('TEAL_USER').$img['savepath'].$img['savename'];
			M('user')->where(array('id'=>$this->uid))->setField('imgurl',$imgurl);
			$this->redirect('User/editset');
		}
	  }
	  /**
	   * 我的乐队页面
	   */
	  public function myband(){
			$band = M('band')->where(array('uid'=>$this->uid))->select();
	//		$bandmember = M('bandmember')->where(array('bandid'=>$band['id']))->select();
			$this->band = $band;
		  	$this->meta_title = '我的乐队';
			$this->display();
	  }
	/**
	 * 修改band页面
	 */
	 public function editband(){
	 	$id = I('id');
		if($id){
			$this->meta_title = '我的乐队';
			$this->band = M('band')->where(array('id'=>$id))->find();
			$this->bandmember = M('bandmember')->where(array('bandid'=>$id))->select();
			$this->display();
		}
	 }
	  /**
	   * 增加与修改乐队与乐队成员
	   */
	 public function edit_bandmember(){
	 	if(IS_POST){
	 		$_POST['num'] = count($_POST['membername']);//乐队成员个数
	 		if($_POST['bandid']){//修改特定乐队及成员
	 			//修改乐队信息（团队成员个数  乐队名字）
	 			$bandid = $_POST['bandid'];
				$_POST['id'] = $bandid;
	 			M('band')->save($_POST);
	 			//先删除乐队成员，再增加
	 			M('bandmember')->where(array('bandid'=>$_POST['bandid']))->delete();
	 		}else{//增加乐队与成员
	 			$uid = $_POST['uid'];
				$bandid = M('band')->add($_POST);
	 		}
			$membername = $_POST['membername'];
			$memberphone = $_POST['memberphone'];
			for($i=0;$i<count($membername);$i++){
				$member['bandid'] = $bandid;
				if($membername[$i]!=''){
					$member['membername'] = $membername[$i];
					$member['memberphone'] = $memberphone[$i];
					M('bandmember')->add($member);
				}
			}
			$this->ajaxReturn($_POST);
	 	}
	 }  
	   
	   
	/**
	 * 我要参加表演页面
	 */
	public function joinact(){
		if($this->user){
			$this->meta_title='参加表演';
			session('join_aid',I('aid'));//记录当前参加的活动ID，注册或登录成功后将跳往此处
			$aid = I('aid');
			$act = M('activity')->where(array('id'=>$aid))->find();//拿到当前活动
//			$instru = M('instruments')->limit(C('INDEX_INSTRU_PAGE'))->page(1)->select();
			$instru = D('ActivityInstrumentListView')->where(array('aid'=>$aid))->select();//当前活动可用乐器
			$band = M('band')->where(array('uid'=>$this->uid))->select();//当前用户乐队
			$this->band = $band;
			$this->assign('instru',$instru);
			$this->assign('act',$act);
			$this->assign('user',$this->user);
			$this->display();
		}else{
			session('join_aid',I('aid'));//记录aid，让注册后跳往详情页
			$this->redirect('User/login',array('aid'=>I('aid')));
		}
	}
	/**
	 * 我要取消表演页面
	 */
	public function cancle_act(){
		if($this->user){
			$aid = I('aid');
			$act = M('activity')->where(array('id'=>$aid))->find();
			$act_event = M('activity_event')->where(array('uid'=>$this->uid,'aid'=>$aid))->find();
			$save = M('activity_event')->where(array('uid'=>$this->uid,'aid'=>$aid))->setField('status',0);
			//发送站内信至指定用户
			$inform['uid'] = $this->uid;
			$inform['content'] = '已取消活动'.$act['title'].'的报名';
			$inform['time'] = time();
			$inform = M('inform')->add($inform);
			$this->ajaxReturn(array('save'=>$save,'inform'=>$inform));
			//$this->redirect('Index/index');
//			$this->redirect('Activity/act_detail/id/'.$aid);
		}else{
			$this->redirect('User/login');
		}
	}
	/**
	 * 提交我要登台的基本信息
	 */
	public function join_act(){
		if(IS_POST){
			//新增报名事件记录
			$_POST['uid']=$this->uid;
			$_POST['applytime']=time();
			$act = M('activity')->where(array('id'=>$_POST['aid']))->find();
			$act_event = M('activity_event')->where(array('uid'=>$this->uid,'aid'=>$_POST['aid']))->find();
			if($act_event){//如果之前报过名,删掉之前的报名记录，重新加
				M('actevent_instrument')->where(array('acteventid'=>$act_event['id']))->delete();
				M('actevent_music')->where(array('acteventid'=>$act_event['id']))->delete();
				M('activity_event')->where(array('id'=>$act_event['id']))->delete();
			}
				if($_POST['bandnametype']=='select_bandname'){//如果是下拉选择的乐队名称
					$_POST['bandname'] = $_POST['select_bandname'];
				}
				$acteventid = M('activity_event')->add($_POST);
				$instrus = $_POST['instru'];
				//新增报名活动乐器
				foreach($instrus as $v){
					$act_ins['acteventid']=$acteventid;
					$act_ins['instrumentid'] = $v;
					M('actevent_instrument')->add($act_ins);
				}
				//新增报名音乐
				if($_POST['m1']){
					$act_music['acteventid']=$acteventid;
					$act_music['musicname']=$_POST['m1'];
					$act_music['musictype']=$_POST['mt1'];
					M('actevent_music')->add($act_music);
				}
				if($_POST['m2']){
					$act_music['acteventid']=$acteventid;
					$act_music['musicname']=$_POST['m2'];
					$act_music['musictype']=$_POST['mt2'];
					M('actevent_music')->add($act_music);
				}
				if($_POST['m3']){
					$act_music['acteventid']=$acteventid;
					$act_music['musicname']=$_POST['m3'];
					$act_music['musictype']=$_POST['mt3'];
					M('actevent_music')->add($act_music);
				}
			//成功报名站内信
			$inform['uid'] = $this->uid;
			$inform['content'] = '已成功报名【'.$act['title'].'】';
			$inform['time'] = time();
			$inform = M('inform')->add($inform);
			$this->ajaxReturn(array('aid'=>$_POST['aid']));
		}
	}
	//分享页面
	public function share(){
		$this->meta_title='分享';
		$this->act = M('activity')->where(array('id'=>I('aid')))->find();
		$this->display('User/share');
	}
	/**
	 * 获取用户的站内信息
	 */
	 public function myinform(){
	 	$this->meta_title='我的信息';
		M('inform')->where(array('uid'=>$this->uid,'islook'=>0))->setField('islook',1);
	 	$myinform = M('inform')->where(array('uid'=>$this->uid))->order(' id desc')->select();
		$this->myinform = $myinform;
		$this->display();
	 }
	 
	
	
	/**
     * 获取cookie进行回填
     */
    public function get_cookie() {
        if (IS_POST) {
            $res = cookie('user_login');
            $res['password'] = think_decrypt($res['password'], 'Hongzhong2015');
            $this->ajaxReturn($res);
        }
    }
	
	/**
     * 登录
     */
    public function logout() {
    	session('uid', null);
		cookie('user_login',null);
		$this->redirect("Index/index");
    }
	
	/**
     * 登录
     */
    public function login() {
        if (IS_POST) {
            $phone    = $_POST['phone'];
            $password = $_POST['password'];
            //$rem_pwd  = I('rem_pwd');
            $rem_pwd  = 1;//默认自动登录
            if (!preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $phone)) {
                $this->error('404');
            }
            $user = M('user')->where(array('phone' => $phone, 'password' => md5($password)))->find();
            if ($user) {
                // 记录登录时间
                $user['ltime'] = time();
                M('User')->save($user);
                // 判断是否要自动登录
                if ($rem_pwd == 1) {
                    // 默认保存7天
                    cookie('user_login', array('phone' => $phone, 'password' => think_encrypt($password, 'Hongzhong2015')), 7 * 24 * 3600);
                }
                session('uid', $user['id']);
				if(I('aid')){//如果是从活动中  我要登台 按钮点击登录成功 ，则跳回活动报名页面
					$this->ajaxReturn(array('url'=>U('User/joinact',array('aid'=>I('aid'),'shareaid'=>I('aid'),'isshare'=>1)),'status'=>1));
				}else{
                	$this->ajaxReturn(array('url' => U('Index/index'), 'status' => 1));
				}
            } else {
                $this->ajaxReturn(array('info' => '用户不存在或密码错误', 'status' => 0));
            }
        } else {
        	
			$this->meta_title='登录';
			$this->aid = I('aid');
            $this->display();
        }
    }

    /**
     * 注册
     * 1、判断短信验证
     * 2、判断号码是否唯一
     */
    public function register() {
    	$aid = session('join_aid');
        if (IS_POST) {
            $phone    = $_POST['phone'];
            $password = $_POST['password'];
            $vcode    = intval($_POST['vcode']);
            // 非法操作
            if ( !(preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $phone) && preg_match('/^[0-9a-zA-Z]{1,32}$/', $password) && $vcode)) {
                $this->error('404');
            }
            // 判断手机号码是否已注册
            if (M('user')->where(array('phone' => $phone))->find()) {
                $this->ajaxReturn(array('id' => '#phone', 'info' => '号码已被注册', 'status' => -1));
            }
            // 检查验证码
            $vcode_arr = session('vcode');
            if ($vcode_arr['phone'] !== $phone || $vcode_arr['vcode'] !== $vcode) {
                $this->ajaxReturn(array('id' => '#vcode', 'info' => '验证码不正确', 'status' => -1));
            }
            $now = time();
            $id  = M('user')->add(array('phone' => $phone, 'password' => md5($password), 'nickname' => '昵称', 'rtime' => $now, 'ltime' => $now, 'imgurl' => __ROOT__.'/Public/Uploads/Img/userimg/face.jpg'));
            if ($id) {
                session('uid', $id);
				if($aid){
					$this->ajaxReturn(array('url'=>U('User/joinact',array('aid'=>$aid,'shareaid'=>$aid,'isshare'=>1)),'status'=>1));
				}else{
					$this->ajaxReturn(array('url' => U('Index/index'), 'status' => 1));	//?'url' => U('User/set')
				}
            } else {
                $this->ajaxReturn(array('info' => '注册失败，请刷新页面后重试', 'status' => 0));
            }
        } else {
            $this->meta_title='注册';
			$this->display();
        }
    }
	
	
	/**
     * 获取注册验证码
     */
    public function get_reg_vcode() {
        $this->_get_validate_code(1);
    }

    /**
     * 获取找回密码验证码
     */
    public function get_repwd_vcode() {
        $this->_get_validate_code(2);
    }

    /**
     * 获取验证码
     * @param integer $type 1、注册 2、找回密码
     */
    private function _get_validate_code($type) {
        $phone = I('p');
        if (!preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $phone)) {  // 判断是否是手机号码
            $res = array('info' => '请输入正确的手机号码', 'status' => 0);
        } elseif ($type === 1 && M('user')->where(array('phone' => $phone))->find()) {  // 判断手机号码是否已注册
            $res = array('info' => '号码已被注册', 'status' => 0);
        } elseif ($type === 2 && !M('user')->where(array('phone' => $phone))->find()) {
            $res = array('info' => '用户不存在', 'status' => 0);
        } elseif ($this->getLastSendtime($phone) > self::SMS_SEND_INTERVAL) {  // 判断上次发送到手机的时间差
            $vcode   = rand(000001, 999999);
            $content = ($type === 1 ? $vcode.'为您的手机验证码，欢迎您注册十五分钟音乐计划' : $vcode.'为手机号码申诉找回验证码，十五分钟音乐计划');
            if (!sendSms($phone, $content)) {
                // 发送失败
                $this->saveSmsSendRecord($phone, $content, $type, 0);
            } else {
                $this->saveSmsSendRecord($phone, $content, $type);
                session('vcode', array('phone' => $phone, 'vcode' => $vcode));
            }
            $res = array('info' => '发送成功，请注意查收手机短信', 'status' => 1);
			
        } else {  // 没到下一次发送短信时间
            $res = array('info' => '还没到下一次发送短信时间', 'status' => 0);
        }
        $this->ajaxReturn($res);
    }

    /**
     * 获取上一次发送短信跟现在的时间差，以秒为单位
     * @param $phone 手机号码
     */
    public function getLastSendtime($phone) {
        // 需要查询数据中，这个号段上一次发送的时间
        $record = M('smsrecord')->field('phone', $phone)->field('type', 1)->field('success', 1)->order('sendtime desc')->limit(1)->select();

        if (!$record) {
            // 如果查询没有，直接返回时间间隔加1
            return self::SMS_SEND_INTERVAL + 1;
        } else {
            // 如果查询到，则把当前时间减去数据库中的时间点，得到毫秒数，并返回；
            return time() - $record[0]['sendtime'];
        }
    }
	
	/**
     * 保存发送短信记录
     * @param String  $phone 手机号码
     * @param String  $content 发送内容
     * @param integer $type 1、注册 2、找回密码
     */
    public function saveSmsSendRecord($phone, $content, $type = 1, $success = 1) {
        M('smsrecord')->add(array('phone' => $phone, 'content' => $content, 'type' => $type, 'success'  => $success, 'sendtime' => time()));
    }


	/**
     * 重置密码
     */
    public function reset_pwd() {
        if (IS_POST) {
            $phone    = $_POST['phone'];
            $password = $_POST['password'];
            $vcode    = intval($_POST['vcode']);
            // 非法操作
            if (!(preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $phone) && preg_match('/^[0-9a-zA-Z]{1,32}$/', $password) && $vcode)) {
                $this->error('404');
            }
            // 判断用户是否存在
            $user = M('user')->where(array('phone' => $phone))->find();
            if (!$user) {
                $this->ajaxReturn(array('id' => '#phone', 'info' => '用户不存在', 'status' => -1));
            }
            // 检查验证码
            $vcode_arr = session('vcode');
            if ($vcode_arr['phone'] !== $phone || $vcode_arr['vcode'] !== $vcode) {
                $this->ajaxReturn(array('id' => '#vcode', 'info' => '验证码不正确', 'status' => -1));
            }
            $user['password'] = md5($password);
            $res = M('user')->save($user) ? array('url' => U('User/login'), 'status' => 1) : array('info' => '密码重置失败，请刷新页面后重试', 'status' => 0);
            $this->ajaxReturn($res);
        } else {
            $this->display('resetpwd');
        }
    }










}